'''
Author: duliang thinktanker@163.com
Date: 2024-06-02 23:10:20
LastEditors: duliang thinktanker@163.com
LastEditTime: 2024-06-02 23:44:19
FilePath:server.py
Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
'''
from paho.mqtt import client as mqtt
import uuid
import json
import time


class MqttClient(object):

    def __init__(self):
        self.mqttClient = self.mqtt_connect()
        # self.on_subscribe()

    def run(self):
        self.on_subscribe()


# mqttClient = MqttClient()

    def on_connect(self, client, userdata, flags, rc):
        """一旦连接成功, 回调此方法"""
        rc_status = [
            "连接成功", "协议版本不正确", "客户端标识符无效", "服务器不可用", "用户名或密码不正确", "未经授权"
        ]
        print("connect：", rc_status[rc])

    def on_message(self, client, userdata, msg):
        """一旦订阅到消息, 回调此方法"""
        # print(type(msg.payload))
        new_msg = str(msg.payload.decode('utf8'))
        # print(type(new_msg))
        new_json = json.loads(new_msg)
        # print(new_json['name'],new_json['msg'])
        name = new_json['name']
        msg_ = new_json['msg']
        if name == 'test2':
            print('收到来自test2的消息')
            print(msg_)
            self.mqtt_publish()
        print("主题:" + msg.topic + " 消息:" + new_msg)

    def mqtt_connect(self):
        """连接MQTT服务器"""
        # mqttClient = mqtt.Client(str(uuid.uuid4()))
        mqttClient = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1,
                                 str(uuid.uuid4()))

        mqttClient.on_connect = self.on_connect  # 返回连接状态的回调函数
        mqttClient.on_message = self.on_message  # 返回订阅消息回调函数
        MQTTHOST = "127.0.0.1"  # MQTT服务器地址
        MQTTPORT = 1883  # MQTT端口
        mqttClient.username_pw_set("test2", "test2")  # mqtt服务器账号密码
        mqttClient.connect(MQTTHOST, MQTTPORT, 60)
        mqttClient.loop_start()  # 启用线程连接

        return mqttClient

    def on_subscribe(self):
        """订阅主题：gate"""
        self.mqttClient.subscribe("gate", 2)
        # mqttClient.loop_forever()
        while True:
            pass

    def mqtt_publish(self):
        """发布主题为'get',内容为'Demo text',服务质量为2"""
        text = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.mqttClient.publish('get', text, 2)
        print("publish:", text)

if __name__ == '__main__':
    myMqttClient = MqttClient()
    myMqttClient.run()
    # on_subscribe()
